﻿using CJAtech.BBS.Business;
using CJAtech.BBS.DataEntity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Web;
using System.Web.Mvc;
using Bigger.Base.Cache;
using Bigger.Framework;
using CJAtech.BBS.Process;
using Bigger.Web.Helper;

namespace CJAtech.BBS.Web.Controllers
{
    public partial class BBSController
    {
        /// <summary>
        /// 轮询是否有最新评论
        /// </summary>
        /// <param name="articleId"></param>
        /// <param name="isReply"></param>
        /// <returns></returns>
        public virtual ActionResult CommentLatest(int? articleId, int? commentID)
        {
            InvokeResult objInvokeResult = new InvokeResult();
            if (!articleId.HasValue)
            {
                objInvokeResult.ResultCode = "ArticleIdNull";
                objInvokeResult.ResultMessage = "文章Id为空";
                return Json(objInvokeResult, JsonRequestBehavior.AllowGet);
            }

            var CurrentCache = Bigger.Core.Cache.CacheHelper.CacheInstance;
            string cacheKey = string.Format("{0}_Article_{1}_LatestComment>{2}", CurrentCommunityConfig.ConfigCode, articleId, commentID);
            object obj = CurrentCache.GetCache(cacheKey);
            if (obj == null)
            {
                BizCommentInfo objBizCommentInfo = new BizCommentInfo(CurrentCommunityConfig.ConnectionStringKey, CurrentCommunityConfig.DataObjectParam);
                if (commentID.HasValue)
                {
                    obj = objBizCommentInfo.GetField<object>("CommentId>@CommentId AND ObjectId=@ObjectId", new { CommentId = commentID, ObjectId = articleId }, "top 1 CommentId");
                }
                else
                {
                    obj = objBizCommentInfo.GetField<object>("ObjectId=@ObjectId", new { ObjectId = articleId }, "top 1 CommentId");
                }
            }
            if (obj == null)
            {
                objInvokeResult.ResultCode = "HasNoLatest";
                objInvokeResult.ResultMessage = "对不起，没有最新评论";
                return Json(objInvokeResult, JsonRequestBehavior.AllowGet);
            }
            CurrentCache.SetCache(cacheKey, obj, TimeSpan.FromSeconds(30));

            objInvokeResult.ResultMessage = "有最新的评论";
            return Json(objInvokeResult, JsonRequestBehavior.AllowGet);
        }
        /// <summary>
        /// 获取热门评论
        /// </summary>
        /// <param name="articleId"></param>
        /// <param name="pageIndex"></param>
        /// <param name="isReply"></param>
        /// <returns></returns>
        public virtual ActionResult CommentHotList(int? articleId, int? pageIndex, int? isReply = 0)
        {
            InvokeResult objInvokeResult = new InvokeResult();
            if (!articleId.HasValue)
            {
                objInvokeResult.ResultCode = "ArticleIdNull";
                objInvokeResult.ResultMessage = "文章Id为空";
                return Json(objInvokeResult, JsonRequestBehavior.AllowGet);
            }
            if (!pageIndex.HasValue || pageIndex < 1)
            {
                pageIndex = 1;
            }
            BizCommentInfo objBizCommentInfo = new BizCommentInfo(CurrentCommunityConfig.ConnectionStringKey, CurrentCommunityConfig.DataObjectParam);
            List<CommentInfo> objCommentInfoList = objBizCommentInfo.GetPageListCache("", TimeSpan.FromSeconds(30), pageIndex.Value - 1, 5, "ObjectId=@ObjectId AND ReplyId=0", new { ObjectId = articleId }, "DiggCount desc");
            if (objCommentInfoList.IsNull())
            {
                objInvokeResult.ResultCode = "CommentHotNull";
                objInvokeResult.ResultMessage = "没有热门评论了";
                return Json(objInvokeResult, JsonRequestBehavior.AllowGet);
            }
            if (isReply.HasValue && isReply.Value == 1)
            {
                LoadReplyList(objCommentInfoList);
            }
            //加载点赞记录
            //LoadCommentInfoRelatedCount(objCommentInfoList);
            //LoadDiggList(objCommentInfoList);
            objInvokeResult.Data = objCommentInfoList;
            return Json(objInvokeResult, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 加载评论列表
        /// </summary>
        /// <param name="articleId">文章Id</param>
        /// <param name="commentID"></param>
        /// <param name="position"></param>
        /// <param name="isReply"></param>
        /// <returns></returns>
        public virtual ActionResult CommentList(int? articleId, int? commentID, string position, int? isReply = 0)
        {
            InvokeResult objInvokeResult = new InvokeResult();
            if (!articleId.HasValue)
            {
                objInvokeResult.ResultCode = "ArticleIdNull";
                objInvokeResult.ResultMessage = "文章Id为空";
                return Json(objInvokeResult, JsonRequestBehavior.AllowGet);
            }
            BizCommentInfo objBizCommentInfo = new BizCommentInfo(CurrentCommunityConfig.ConnectionStringKey, CurrentCommunityConfig.DataObjectParam);
            List<CommentInfo> objCommentInfoList = null;
            int commentCount = 0;
            if (commentID.HasValue)
            {
                if (position == "top")
                {
                    objCommentInfoList = objBizCommentInfo.GetListCache("", TimeSpan.FromSeconds(5), "ObjectId='" + articleId + "' AND IsAudit=1 AND CommentId>" + commentID, "CommentId asc", "top 10 *");
                }
                else
                {
                    objCommentInfoList = objBizCommentInfo.GetListCache("", TimeSpan.FromSeconds(5), "ObjectId='" + articleId + "' AND IsAudit=1 AND CommentId<" + commentID, "CommentId desc", "top 10 *");
                }
            }
            else
            {
                objCommentInfoList = objBizCommentInfo.GetList("ObjectId='" + articleId + "' AND IsAudit=1", "CommentId desc", "top 10 *");
                commentCount = objBizCommentInfo.GetTotal("ObjectId='" + articleId + "' AND IsAudit=1");
            }
            if (objCommentInfoList.IsNull())
            {
                objInvokeResult.ResultCode = "CommentNull";
                objInvokeResult.ResultMessage = "没有更多评论了";
                return Json(objInvokeResult, JsonRequestBehavior.AllowGet);
            }
            if (isReply.HasValue && isReply.Value == 1)
            {
                LoadReplyList(objCommentInfoList);
            }
            //加载点赞记录
            //LoadCommentInfoRelatedCount(objCommentInfoList);
            //LoadDiggList(objCommentInfoList);
            objInvokeResult.Data = new { CommentList = objCommentInfoList, CommentCount = commentCount };
            return Json(objInvokeResult, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 加载评论列表
        /// </summary>
        /// <param name="articleId">文章Id</param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public virtual ActionResult CommentPageList(int? articleId, int? pageIndex = 1, int? pageSize = 10, int? isReply = 0)
        {
            InvokeResult objInvokeResult = new InvokeResult();
            if (!articleId.HasValue)
            {
                objInvokeResult.ResultCode = "ArticleIdNull";
                objInvokeResult.ResultMessage = "文章Id为空";
                return Json(objInvokeResult, JsonRequestBehavior.AllowGet);
            }
            BizCommentInfo objBizCommentInfo = new BizCommentInfo(CurrentCommunityConfig.ConnectionStringKey, CurrentCommunityConfig.DataObjectParam);
            if (!pageIndex.HasValue || pageIndex <= 0)
            {
                pageIndex = 1;
            }
            if (!pageSize.HasValue || pageSize <= 0 || pageSize > 20)
            {
                pageSize = 10;
            }
            //加载点赞记录
            //LoadCommentInfoRelatedCount(objCommentInfoList);
            //LoadDiggList(objCommentInfoList);
            int recordCount = 0;
            List<CommentInfo> objCommentInfoList = objBizCommentInfo.GetPageListCache("", TimeSpan.FromSeconds(5), pageIndex.Value - 1, pageSize.Value, out recordCount, "ObjectId='" + articleId + "' AND IsAudit=1", "CommentId desc");
            if (isReply.HasValue && isReply.Value == 1)
            {
                LoadReplyList(objCommentInfoList);
            }
            objInvokeResult.Data = new { CommentList = objCommentInfoList, CommentCount = recordCount, PageIndex = pageIndex, PageSize = pageSize, PageCount = (int)Math.Ceiling(((double)recordCount / pageSize.Value)) };
            return Json(objInvokeResult, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 添加评论
        /// </summary>
        /// <param name="articleId"></param>
        /// <param name="replyId"></param>
        /// <param name="content"></param>
        /// <returns></returns>
        [HttpPost]
        [ValidateInput(false)]
        public virtual ActionResult AddComment(int? articleId, int? replyId, string content)
        {
            InvokeResult objInvokeResult = new InvokeResult();
            if (!articleId.HasValue)
            {
                objInvokeResult.ResultCode = "ArticleIdEmpty";
                objInvokeResult.ResultMessage = "对不起，文章不存在";
                return Json(objInvokeResult);
            }
            if (content.IsNull())
            {
                objInvokeResult.ResultCode = "ContentEmpty";
                objInvokeResult.ResultMessage = "对不起，评论内容不能为空";
                return Json(objInvokeResult);
            }
            var badwordsList = content.SearchMatchBadWords(CurrentCommunityConfig.ConnectionStringKey, CurrentCommunityConfig.DataObjectParam);
            if (badwordsList.IsNoNull())
            {
                objInvokeResult.ResultCode = "ContentHasBadWords";
                objInvokeResult.ResultMessage = "对不起，评论内容包含敏感信息词汇 " + badwordsList[0];
                return Json(objInvokeResult);
            }

            var CurrentCache = Bigger.Core.Cache.CacheHelper.CacheInstance;
            string cacheKey = this.CurrentCommunityConfig.ConfigCode + "_LastComment_" + this.CurrentUserInfo.UserId;
            //获取上一次评论缓存
            CommentInfo objLastCommentInfo = CurrentCache.GetCache<CommentInfo>(cacheKey);
            if (objLastCommentInfo != null && objLastCommentInfo.CreateDate.AddSeconds(5).IsGreaterThanCurrent())
            {
                objInvokeResult.ResultCode = "CommentFrequently";
                objInvokeResult.ResultMessage = "对不起，请你与上次评论间隔5秒";
                return Json(objInvokeResult);
            }

            BizCommentInfo objBizCommentInfo = new BizCommentInfo(CurrentCommunityConfig.ConnectionStringKey, CurrentCommunityConfig.DataObjectParam);
            CommentInfo objRepliedComment = null;
            if (replyId.HasValue)
            {
                objRepliedComment = objBizCommentInfo.GetRecordCache("", replyId.Value);
                if (objRepliedComment == null)
                {
                    objInvokeResult.ResultCode = "ReplyNull";
                    objInvokeResult.ResultMessage = "对不起，被回复的评论不存在或已删除";
                    return Json(objInvokeResult);
                }
            }

            CommentInfo objCommentInfo = new CommentInfo()
            {
                ObjectId = articleId.Value.ToString(),
                ObjectCode = "Article_" + articleId,
                UserId = CurrentUserInfo.UserId,
                NickName = CurrentUserInfo.UserName.SetNullToDefaultValue(string.Empty),
                Content = content,
                IsAudit = 1,
                UserIP = SystemWebAsset.GetClientIP(),
                CreateDate = DateTime.Now,
                ReplyId = objRepliedComment == null ? 0 : objRepliedComment.CommentId,
                Avatar = CurrentUserInfo.Avatar.SetNullToDefaultValue(string.Empty)
            };
            objInvokeResult.ResultMessage = "评论成功";
            objInvokeResult.Data = objBizCommentInfo.Add(objCommentInfo);
            if (objRepliedComment != null)
            {
                objCommentInfo.ReplyIdPath = objRepliedComment.ReplyIdPath + objCommentInfo.CommentId + ",";
            }
            else
            {
                objCommentInfo.ReplyIdPath = "," + objCommentInfo.CommentId + ",";
            }
            objBizCommentInfo.Update("ReplyIdPath=@ReplyIdPath", objCommentInfo.CommentId, new { ReplyIdPath = objCommentInfo.ReplyIdPath });

            //设置上一条评论缓存
            CurrentCache.SetCache(cacheKey, objCommentInfo, TimeSpan.FromSeconds(10));

            //更新文章的评论数
            BizArticleInfo objBizArticleInfo = new BizArticleInfo(CurrentCommunityConfig.ConnectionStringKey, CurrentCommunityConfig.DataObjectParam);
            objBizArticleInfo.Update("CommentCount=CommentCount+1", articleId.Value);
            return Json(objInvokeResult);
        }

        /// <summary>
        /// 评论点赞
        /// </summary>
        /// <param name="commentId"></param>
        /// <param name="articleId"></param>
        /// <returns></returns>
        public virtual ActionResult DiggComment(int? commentId, int? articleId)
        {
            InvokeResult objInvokeResult = new InvokeResult();
            if (!commentId.HasValue)
            {
                objInvokeResult.ResultCode = "CommentIdEmpty";
                objInvokeResult.ResultMessage = "对不起，评论不存在";
                return Json(objInvokeResult);
            }
            if (!articleId.HasValue)
            {
                objInvokeResult.ResultCode = "ArticleIdEmpty";
                objInvokeResult.ResultMessage = "对不起，文章不存在";
                return Json(objInvokeResult);
            }
            BizCommentInfo objBizCommentInfo = new BizCommentInfo(CurrentCommunityConfig.ConnectionStringKey, CurrentCommunityConfig.DataObjectParam);
            CommentInfo objCommentInfo = objBizCommentInfo.GetRecord(commentId.Value);
            if (objCommentInfo == null)
            {
                objInvokeResult.ResultCode = "CommentInfoEmpty";
                objInvokeResult.ResultMessage = "对不起，评论不存在";
                return Json(objInvokeResult);
            }

            BizDiggInfo objBizDiggInfo = new BizDiggInfo(CurrentCommunityConfig.ConnectionStringKey, CurrentCommunityConfig.DataObjectParam);
            bool hasDigg = objBizDiggInfo.Any("ObjectType='Digg' AND UserId=@UserId AND ObjectId=@ObjectId AND ObjectCode=@ObjectCode",new{UserId=this.CurrentUserInfo.UserId,ObjectId=commentId.Value,ObjectCode="Article_Comments_" + articleId} );
            if (hasDigg)
            {
                objInvokeResult.ResultCode = "DiggAlready";
                objInvokeResult.ResultMessage = "对不起，你已对该评论点赞过";
                return Json(objInvokeResult);
            }
            DiggInfo objDiggInfo = new DiggInfo
            {
                ObjectId = commentId.Value.ToString(),
                ObjectCode = "Article_Comments_" + articleId,
                ObjectType = "Digg",
                UserId = this.CurrentUserInfo.UserId,
                UserIP = SystemWebAsset.GetClientIP(),
                DiggTime = DateTime.Now
            };
            objBizDiggInfo.Add(objDiggInfo);

            //更新评论点赞
            objBizCommentInfo.Update("DiggCount=DiggCount+1", objCommentInfo.CommentId);

            objInvokeResult.ResultMessage = "点赞成功";
            return Json(objInvokeResult);
        }

        protected virtual void LoadDiggList(List<CommentInfo> objList)
        {
            if (objList.IsNoNull())
            {
                BizDiggInfo objBizDiggInfo = new BizDiggInfo(CurrentCommunityConfig.ConnectionStringKey, CurrentCommunityConfig.DataObjectParam);
                string objectIDs = objList.Select(c => c.CommentId).JoinComma().ConvertVarcharString();
                List<DiggInfo> objDiggInfoList = objBizDiggInfo.GetListCache("", TimeSpan.FromSeconds(5), string.Format("ObjectType='Digg' AND ObjectId in({0}) AND UserId='{1}'", objectIDs, this.CurrentUserInfo.UserId));
                if (objDiggInfoList.IsNoNull())
                {
                    foreach (CommentInfo objCommentInfo in objList)
                    {
                        objCommentInfo.IsDigg = objDiggInfoList.Any(c => c.ObjectId == objCommentInfo.CommentId.ToString());
                    }
                }
            }
        }

        protected virtual void LoadReplyList(List<CommentInfo> objList)
        {
            if (objList.IsNoNull())
            {
                string replyIdPath;
                List<string> objReplyIds = new List<string>();
                foreach (CommentInfo objCommentInfo in objList)
                {
                    if (objCommentInfo.ReplyId == 0)
                    {
                        continue;
                    }
                    replyIdPath = objCommentInfo.ReplyIdPath.Trim(',').Replace("," + objCommentInfo.CommentId, "");
                    objReplyIds.AddRange(replyIdPath.Split(','));
                }
                if (objReplyIds.IsNoNull())
                {
                    CommentInfo objCommentInfoExist = null;
                    objReplyIds = objReplyIds.Distinct().ToList();//Id排重
                    List<CommentInfo> objReplyList = new List<CommentInfo>();
                    for (int i = objReplyIds.Count - 1; i >= 0; i--)
                    {
                        objCommentInfoExist = objList.FirstOrDefault(c => string.Equals(objReplyIds[i], c.CommentId.ToString()));
                        if (objCommentInfoExist != null)
                        {
                            //若现有评论已有回复的评论，从内存取
                            objReplyList.Add(objCommentInfoExist);
                            objReplyIds.Remove(objReplyIds[i]);
                        }
                    }
                    if (objReplyIds.IsNoNull())
                    {
                        BizCommentInfo objBizCommentInfo = new BizCommentInfo(CurrentCommunityConfig.ConnectionStringKey, CurrentCommunityConfig.DataObjectParam);
                        //剩下的回复读数据库
                        List<CommentInfo> objRest = objBizCommentInfo.GetListInCache("", TimeSpan.FromSeconds(5), objReplyIds.JoinComma());
                        if (objRest.IsNoNull())
                        {
                            objReplyList.AddRange(objRest);
                        }
                    }
                    foreach (CommentInfo objCommentInfo in objList)
                    {
                        if (objCommentInfo.ReplyId == 0)
                        {
                            continue;
                        }
                        replyIdPath = objCommentInfo.ReplyIdPath.Replace("," + objCommentInfo.CommentId, "");
                        //组织评论回复
                        objCommentInfo.ReplyList = objReplyList.Where(c => replyIdPath.Contains(string.Format(",{0},", c.CommentId))).OrderBy(c => c.CommentId).ToList();
                    }
                }
            }
        }
    }

    /*
    评论逻辑：
       新增评论1：ReplyId：0，ReplyIdPath：,1,                  设Id 1
       回复评论1：ReplyId：1，ReplyIdPath：,1,2,                设Id 2
       回复评论1：ReplyId：1，ReplyIdPath：,1,3,                设Id 3
       回复评论2：ReplyId：2，ReplyIdPath：,1,2,4,              设Id 4
       回复评论2：ReplyId：2，ReplyIdPath：,1,2,5,              设Id 5
       回复评论4：ReplyId：4，ReplyIdPath：,1,2,4,6,            设Id 6
       回复评论4：ReplyId：4，ReplyIdPath：,1,2,4,7,            设Id 7
    */

    /*
    评论逻辑：
       新增评论1：ReplyId：0，ReplyIdPath：,1,                  设Id 1
       回复评论1：ReplyId：1，ReplyIdPath：,1,2,                设Id 2
       回复评论1：ReplyId：1，ReplyIdPath：,1,3,                设Id 3
       回复评论2：ReplyId：1，ReplyIdPath：,1,2,4,              设Id 4
       回复评论2：ReplyId：1，ReplyIdPath：,1,2,5,              设Id 5
       回复评论4：ReplyId：1，ReplyIdPath：,1,2,4,6,            设Id 6
       回复评论4：ReplyId：1，ReplyIdPath：,1,2,4,7,            设Id 7
    */

    //需求 切换资源
}
